<template>
  <div class="sold-products-container">
    <!-- 顶部固定的状态筛选标签栏 -->
    <el-affix :offset="0">
      <!-- 订单状态切换标签，切换时触发handleStatusChange事件 -->
      <el-tabs v-model="activeStatus" class="status-tabs" @tab-change="handleStatusChange">
        <el-tab-pane label="全部" name="全部"></el-tab-pane>
        <el-tab-pane label="待支付" name="待支付"></el-tab-pane>
        <el-tab-pane label="待发货" name="待发货"></el-tab-pane>
        <el-tab-pane label="待收货" name="待收货"></el-tab-pane>
        <el-tab-pane label="已完成" name="已完成"></el-tab-pane>
        <el-tab-pane label="已取消" name="已取消"></el-tab-pane>
      </el-tabs>
    </el-affix>

    <!-- 可滚动的订单列表区域，滚动时触发handleScroll事件（用于实现无限加载） -->
    <el-scrollbar class="product-scrollbar" @scroll="handleScroll">
      <div class="product-list">
        <!-- 订单卡片列表，遍历displayOrders数组 -->
        <el-card v-for="order in displayOrders" :key="order.id" class="product-card" shadow="hover">
          <div class="product-content">
            <!-- 商品图片展示区域 -->
            <el-image 
              class="product-image" 
              :src="order.product_image || DEFAULT_IMAGE" 
              fit="cover"
              :loading="true"
            >
              <!-- 图片加载中的占位内容 -->
              <template #placeholder>
                <div class="image-loading">
                  <el-icon class="is-loading"><Loading /></el-icon>
                </div>
              </template>
              <!-- 图片加载失败的占位内容 -->
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            
            <!-- 订单信息展示区域 -->
            <div class="product-info">
              <!-- 订单头部：订单号和创建时间 -->
              <div class="order-header">
                <span class="order-code">订单号: {{ order.order_code }}</span>
                <span class="order-time">{{ formatTime(order.create_time) }}</span>
              </div>
              <!-- 商品名称，如果商品已下架则显示提示文本 -->
              <div class="product-name">
                {{ order.product_name || (order.product_title || '商品已下架') }}
              </div>
              <!-- 商品价格 -->
              <div class="product-price">¥{{ order.snapshot_price }}</div>
              <!-- 订单底部：状态标签和卖家信息 -->
              <div class="order-footer">
                <el-tag :type="getStatusType(order.status_display)">
                  {{ order.status_display }}
                </el-tag>
                <span class="seller-info">卖家: {{ order.seller_name }}</span>
              </div>
              <div class="action-buttons">
                <!-- 查看详情按钮 -->
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewDetails(order.order_code)" 
                  class="detail-btn">
                  查看详情
                </el-button>
                <!-- 确认收货按钮，仅在待收货状态显示 -->
                <el-button 
                  v-if="order.status_display === '待收货'"
                  type="success" 
                  size="small" 
                  @click="confirmReceive(order.order_code)"
                  class="receive-btn">
                  确认收货
                </el-button>
                <!-- 评价按钮，仅在已完成且未评价时显示 -->
                <el-button 
                  v-if="order.status_display === '已完成' && !order.has_reviewed"
                  type="warning" 
                  size="small" 
                  @click="goToReview(order.order_code)"
                  class="review-btn">
                  去评价
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 加载状态提示 -->
        <div v-if="loading" class="loading-more">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        <!-- 无更多数据提示 -->
        <div v-if="!hasMore" class="no-more-data">没有更多数据了</div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Picture, Loading } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { DEFAULT_IMAGE } from '@/utils/orderUtils'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiClient from '@/utils/request'
const router = useRouter()

// 状态管理
const orders = ref([])
const activeStatus = ref('全部')
const currentPage = ref(1)
const loading = ref(false)
const hasMore = ref(true)

// 订单列表计算属性
const displayOrders = computed(() => {
  if (activeStatus.value === '全部') {
    return orders.value
  }
  return orders.value.filter(order => order.status_display === activeStatus.value)
})

// 加载订单数据
const loadOrders = async (page = 1) => {
  try {
    loading.value = true
    const token = localStorage.getItem('access_token')
    if (!token) {
      router.push('/login')
      return
    }

    const params = { 
      page,
      role: 'buyer'  // 明确指定以买家身份查看
    }
    if (activeStatus.value !== '全部') {
      params.status = getStatusCode(activeStatus.value)
    }

    const response = await apiClient.get('/api/orders/', {
      params,
    })

    const { results, next } = response.data
    
    if (page === 1) {
      orders.value = results
    } else {
      orders.value = [...orders.value, ...results]
    }
    
    hasMore.value = !!next
    
    // 获取每个订单对应的商品信息和评价状态
    await Promise.all(results.map(async (order) => {
      await loadProductDetails(order)
      await checkReviewStatus(order)
    }))
    
  } catch (error) {
    console.error('获取订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取商品详情
const loadProductDetails = async (order) => {
  try {
    const response = await apiClient.get(`/api/products/buyer/${order.product_code}/`)
    order.product_name = response.data.name
    order.product_image = response.data.images?.[0]?.url
  } catch (error) {
    console.error(`获取商品 ${order.product_code} 详情失败:`, error)
    order.product_name = '商品已下架或被删除'
    order.product_image = DEFAULT_IMAGE
  }
}

// 检查评价状态
const checkReviewStatus = async (order) => {
  try {
    const token = localStorage.getItem('access_token')
    const response = await apiClient.get(`/api/orders/reviews/?order=${order.id}`)
    order.has_reviewed = response.data.results.length > 0
  } catch (error) {
    console.error('检查评价状态失败:', error)
    order.has_reviewed = false
  }
}

// 状态码转换
const getStatusCode = (statusDisplay) => {
  const statusMap = {
    '待支付': 0,
    '待发货': 1,
    '待收货': 2,
    '已完成': 3,
    '已取消': 4
  }
  return statusMap[statusDisplay]
}

// 格式化时间
const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleString()
}

// 状态标签样式
const getStatusType = (status) => {
  const types = {
    '待支付': 'danger',
    '待发货': 'warning',
    '待收货': 'primary',
    '已完成': 'success',
    '已取消': 'info'
  }
  return types[status] || ''
}

// 处理状态切换
const handleStatusChange = (status) => {
  activeStatus.value = status
  currentPage.value = 1
  orders.value = []
  hasMore.value = true
  loadOrders(1)
}

// 处理滚动加载
const handleScroll = ({ scrollTop, clientHeight, scrollHeight }) => {
  if (scrollHeight - scrollTop <= clientHeight + 50 && !loading.value && hasMore.value) {
    currentPage.value++
    loadOrders(currentPage.value)
  }
}

// 查看订单详情
const viewDetails = (orderCode) => {
  router.push({ 
    name: 'ordersDetail', 
    params: { order_code: orderCode },
     query: {
      from: '/Mine/maidao'  // 明确指定来源
    }
  })
}

// 确认收货
const confirmReceive = async (orderCode) => {
  try {
    await ElMessageBox.confirm('确认收到商品了吗？', '确认收货', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const token = localStorage.getItem('access_token')
    await apiClient.post(`/api/orders/${orderCode}/complete/`, {})

    ElMessage.success('收货成功！')
    // 刷新当前订单状态
    const order = orders.value.find(o => o.order_code === orderCode)
    if (order) {
      order.status_display = '已完成'
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error(error.response?.data?.message || '确认收货失败')
    }
  }
}

// 去评价
const goToReview = (orderCode) => {
  router.push({ 
    path: `/orders/${orderCode}/review`,
    params: { order_code: orderCode }
  })
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.order-code {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.order-time {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.order-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 8px 0;
}

.seller-info {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.action-buttons {
  display: flex;
  gap: 8px;
  margin-top: 10px;
}

.action-buttons .el-button {
  flex: 1;
}

.sold-products-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
}

.status-tabs {
  background-color: var(--el-bg-color);
  padding: 0 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.status-tabs :deep(.el-tabs__header) {
  margin: 0;
}

.status-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.product-scrollbar {
  flex: 1;
  padding: 20px;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.product-card {
  transition: all 0.3s;
  border-radius: 8px;
}

.product-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.1);
}

.product-content {
  display: flex;
  gap: 15px;
}

.product-image {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-light);
  color: var(--el-text-color-placeholder);
}

.image-loading {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-light);
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 44px;
}

.product-price {
  font-size: 18px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin: 8px 0;
}

.product-status {
  margin: 8px 0;
}

.loading-more {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: var(--el-text-color-secondary);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.no-more-data {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: var(--el-text-color-secondary);
}
</style>